/**
 * <b>项目名称：</b>网络应用框架<br/>
 * <b>包    名：</b>com.hhwy.framework.datasource<br/>
 * <b>文 件 名：</b>DatasourceHelper.java<br/>
 * <b>版本信息：</b><br/>
 * <b>日    期：</b>2014年8月4日-下午3:56:04<br/>
 * <b>Copyright (c)</b> 2014恒华伟业科技股份有限公司-版权所有<br/>
 * 
 */
package com.hhwy.framework.datasource;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Iterator;

import javax.sql.DataSource;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSource;
import com.hhwy.framework.configure.ConfigHelper;
import com.hhwy.framework.datasource.domain.DatasourceConfig;
import com.hhwy.framework.exception.ConfigException;
import com.hhwy.framework.persistent.dialect.DatabaseExt;
import com.hhwy.framework.util.IoTools;

 /**
 * <b>类 名 称：</b>DatasourceHelper <br/>
 * <b>类 描 述：</b>数据源、动态数据源的创建<br/>
 * <b>创 建 人：</b>lihuiming<br/>
 * <b>修 改 人：</b>Administrator<br/>
 * <b>修改时间：</b>2014年8月4日 下午3:56:04<br/>
 * <b>修改备注：</b><br/>
 * @version 1.0.0<br/>
 */
public class DatasourceHelper {
	
	static Logger log = LoggerFactory.getLogger(DatasourceHelper.class);
	
	public static String DATABASE_TYPE ;
	
	//static Properties props = null;
	/**数据源属性配置前缀*/
	static String propertyPrefix = "ds.";
	/**默认数据源配置*/
	static DatasourceConfig defaultDc = new DatasourceConfig();
	private static  boolean showSql = false;
	private static  boolean generalDDL = false;
	private static  DatabaseExt database = DatabaseExt.MYSQL;
	
	private static DruidDataSource dds = null;
	
	static{
		//Resource resource = new ClassPathResource("db.properties");
		
		try {
			//props = PropertiesLoaderUtils.loadProperties(resource);
			
			getDataSourceConfig();
			
			showSql = Boolean.parseBoolean(ConfigHelper.getConfig("hibernate.showSql"));
			generalDDL = Boolean.parseBoolean(ConfigHelper.getConfig("hibernate.generalDDL"));
			database = getDatabase(ConfigHelper.getConfig("hibernate.database").toString());
			
		} catch (Exception e) {
			new ConfigException("配置异常!", e).printStackTrace();
		} 
	}
	/**
	 * getDatasourceConfig(描述这个方法的作用)<br/>
	 * @return 
	 * DatasourceConfig
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @exception 
	 * @since  1.0.0
	*/
	private static void getDataSourceConfig() throws Exception {
		Iterator<String> it = BeanUtils.describe(defaultDc).keySet().iterator();
		while(it.hasNext()){
			String key = it.next();
			String propertyKey = propertyPrefix+key;
			Object value = ConfigHelper.getConfig(propertyKey);
			if(value != null)
				BeanUtils.setProperty(defaultDc, key, value);
			
		}
		
	}
	/**
	 * getDatabase(数据库类型)<br/>
	 * @param db
	 * @return 
	 * DatabaseExt
	 * @exception 
	 * @since  1.0.0
	 */
	private static DatabaseExt getDatabase(String db) {
		DatabaseExt dbe = null;
		
		if(db.equals(DatabaseExt.SQLITE.toString()))
			dbe = DatabaseExt.SQLITE;
		else if(db.equals(DatabaseExt.ORACLE.toString()))
			dbe = DatabaseExt.ORACLE;
		else if(db.equals(DatabaseExt.MYSQL.toString()))
			dbe = DatabaseExt.MYSQL;
		else
			dbe = DatabaseExt.DEFAULT;
		
		DATABASE_TYPE = dbe.toString().toLowerCase();
		
		return dbe;
	}
	/**
	 * getDatasource(创建数据源)<br/>
	 * @param dc
	 * @return 
	 * DataSource
	 * @exception 
	 * @since  1.0.0
	 */
	public static DataSource getDataSource(DatasourceConfig dc){
		DruidDataSource ds = new DruidDataSource();
		ds = new DruidDataSource();
		ds.setDriverClassName(dc.getDriver());
		String dbUrl = dc.getUrl();
		if(dbUrl.indexOf("${base.path}") > -1)
			dbUrl = dbUrl.replace("${base.path}", IoTools.getABSPATH());
		ds.setUrl(dbUrl);
		log.info("dds.url==="+dbUrl);
		ds.setUsername(dc.getUserName());
		ds.setPassword(dc.getPassword());
		ds.setInitialSize(dc.getInitialSize());
		ds.setMaxActive(dc.getMaxActive());
		ds.setMinIdle(dc.getMinIdle());
		ds.setValidationQuery(dc.getValidationQuery());
		ds.setTestOnBorrow(dc.isTestOnBorrow());
		ds.setTestOnReturn(dc.isTestOnReturn());
		ds.setTestWhileIdle(dc.isTestWhileIdle());
		ds.setTimeBetweenEvictionRunsMillis(dc.getTimeBetweenEvictionRunsMillis());
		ds.setMinEvictableIdleTimeMillis(dc.getMinEvictableIdleTimeMillis());
		ds.setRemoveAbandoned(dc.isRemoveAbandoned());
		ds.setRemoveAbandonedTimeout(dc.getRemoveAbandonedTimeout());
		try{
			ds.setFilters(dc.getFilters());
		} catch (SQLException e) {
			new ConfigException("配置异常!", e).printStackTrace();
		}
		return ds;
	}
	/**
	 * getDefaultDatasource(获取默认数据源)<br/>
	 * @return 
	 * DataSource
	 * @exception 
	 * @since  1.0.0
	 */
	public static  DataSource getDefaultDataSource(){
		
		if(dds == null ){
			
			dds = (DruidDataSource)getDataSource(defaultDc);
		}
		if(!dds.isEnable()){
			try {
				dds.restart();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return dds;
	}

	public static boolean isShowSql() {
		return showSql;
	}
	public static boolean isGeneralDDL() {
		return generalDDL;
	}
	public static DatabaseExt getDatabase() {
		return database;
	}
}
